<template>
  <ie-page>

    <template #extra>
      <n-space>
        <template v-if="checkedRowKeys.length">
          <n-popconfirm
            :on-positive-click="handleBatchDelete"
          >
            <template #trigger>
              <n-button>批量删除</n-button>
            </template>
            请确定是否删除选中的 {{ checkedRowKeys.length }} 条数据？
          </n-popconfirm>
          <n-divider vertical style="height: 34px;" />
        </template>
        <n-button type="primary" @click="$router.push({ name: 'SystemUserCreate' })">新增后台用户</n-button>
      </n-space>
    </template>

    <ie-table-query :model="SystemUserModel" />

    <ie-table
      :model="SystemUserModel"
      :actions="['delete', 'revert', 'edit']"
      :row-key="row => row.id"
      v-model:checked-row-keys="checkedRowKeys"
      @delete:row="handleDelete"
      @revert:row="handleRevert"
      @edit:row="handleEdit"
      ref="tableRef"
    />
  </ie-page>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useMutation } from 'villus'

import SystemUserModel from '/@/model/system-user'
import { createDelete, createRevert } from '/@/graphql'

const router = useRouter()

const tableRef = ref()
const checkedRowKeys = ref([])

function handleEdit(row) {
  router.push({
    name: 'SystemUserId',
    params: {
      id: row.id
    }
  })
}

const { execute: remove } = useMutation(
  createDelete(SystemUserModel, 'id', true, 'uuid')
)

function handleDelete(row, refresh) {
  remove({ ids: [row.id] }).then(refresh)
}

function handleBatchDelete() {
  if (checkedRowKeys.value.length) {
    remove({
      ids: checkedRowKeys.value
    }).then(tableRef.value?.refresh)
  }
}

const { execute: revert } = useMutation(
  createRevert(SystemUserModel, 'id', 'uuid')
)

function handleRevert(row, refresh) {
  revert({ ids: [row.id] }).then(refresh)
}
</script>